package cn.iocoder.yudao.module.product.service.comment;


import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.product.controller.app.comment.vo.CommentLikeReqVO;
import cn.iocoder.yudao.module.product.dal.dataobject.comment.CommentLikeDO;
import cn.iocoder.yudao.module.product.dal.mysql.comment.CommentLikeMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_ALREADY_LIKE;

@Service
@Validated
public class CommentLikeServiceImpl implements CommentLikeService{

    @Resource
    private CommentLikeMapper commentLikeMapper;
    @Override
    public void likeComment(CommentLikeReqVO reqVO) {
          Long userId=getLoginUserId();
        CommentLikeDO like = commentLikeMapper.selectByUserIdAndCommentId(userId, reqVO.getCommentId());
        if (like != null) {
            throw exception(USER_ALREADY_LIKE);
        }
        // 创建新的点赞记录
        CommentLikeDO newLike = BeanUtils.toBean(reqVO, CommentLikeDO.class);
        newLike.setUserId(userId);
        commentLikeMapper.insert(newLike);
    }

    @Override
    public void unlikeComment(CommentLikeReqVO reqVO) {
        Long userId=getLoginUserId();
        CommentLikeDO like = commentLikeMapper.selectByUserIdAndCommentId(userId, reqVO.getCommentId());
        if (like == null) {
            throw exception(USER_ALREADY_LIKE);
        }
        commentLikeMapper.deleteById(like.getId());
    }
}
